import CryptoJS from 'crypto-js';
const secretKey = 'X8$aG2@9kY%mF7rP';

const userInfoString = JSON.stringify({
  "token": "",
  "expire": "",
  "userRole": "",
  "companyAdmin": true,
  "userInfo": {},
  "companyInfo": {}
});
const temp = CryptoJS.AES.encrypt(userInfoString, secretKey).toString();
const state = {
  language: localStorage.getItem('language') ? localStorage.getItem('language') : 'zh',
  userInfo: localStorage.getItem('userInfo') ? localStorage.getItem('userInfo') : temp,
};

const getters = {
  userInfo(state) {
    const encryptedUserInfo = state.userInfo;
    if (encryptedUserInfo) {
      const bytes = CryptoJS.AES.decrypt(encryptedUserInfo, secretKey);
      const decryptedUserInfo = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
      return decryptedUserInfo;
    }
    return null;
  }
}

const mutations = {
  setLanguage(state, data) {
    state.language = data;
    localStorage.setItem('language', data)
  },
  setUserInfo(state, data) {
    const userInfoString = JSON.stringify(data);
    const encrypted = CryptoJS.AES.encrypt(userInfoString, secretKey).toString();
    localStorage.setItem('userInfo', encrypted)
    state.userInfo = encrypted;
  },
};

const actions = {
  setLanguage({ commit }, data) {
    commit('setLanguage', data); // 存储字典数据到 state
  },
  setUserInfo({ commit }, data) {
    commit('setUserInfo', data); // 存储字典数据到 state
  },
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};
